package com.boarsoft.rpc.http.jetty.handler;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.boarsoft.common.util.HttpClientUtil;
import com.boarsoft.common.util.JsonUtil;
import com.boarsoft.common.util.StreamUtil;
import com.boarsoft.rpc.bean.RpcCall;

public class DefaultJsonIoHandler implements IoHandler {
	/** */
	protected String charset = "UTF-8";
	/** */
	protected String contentType = "application/json; charset=UTF-8";

	@Override
	public RpcCall read(RpcCall co, String target, HttpServletRequest req, HttpServletResponse rsp)
			throws IOException, ClassNotFoundException {
		String body = HttpClientUtil.readStr(req.getInputStream(), charset);
		String[] arr = body.split("\n");
		Object[] arguments = new Object[arr.length];
		co.setArguments(arguments);
		for (int i = 0; i < arguments.length; i++) {
			String ln = arr[i];
			int j = ln.indexOf("=");
			String className = ln.substring(0, j);
			String json = ln.substring(j + 1);
			Class<?> clazz = Class.forName(className);
			arguments[i] = JsonUtil.parseObject(json, clazz);
		}
		// long methodExeNo;
		// Integer callback;
		// String traceId;
		return co;
	}

	@Override
	public void write(RpcCall co, String target, HttpServletRequest req, HttpServletResponse rsp) throws IOException {
		if (co.getThrowable() != null) {
			rsp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
			return;
		}
		Object result = co.getResult();
		rsp.setContentType(contentType);
		rsp.setHeader("className", result == null ? "" : result.getClass().getName());
		PrintWriter writer = null;
		try {
			writer = rsp.getWriter();
			writer.write(JsonUtil.toJSONString(result));
			rsp.flushBuffer();
		} catch (IOException e) {
			StreamUtil.close(writer);
		}
	}

	public String getContentType() {
		return contentType;
	}

	public void setContentType(String contentType) {
		this.contentType = contentType;
	}

	public String getCharset() {
		return charset;
	}

	public void setCharset(String charset) {
		this.charset = charset;
	}
}
